/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.web.ext.ckez;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.zkoss.zk.au.http.AuExtension;
import org.zkoss.zk.au.http.DHtmlUpdateServlet;
import org.zkoss.zk.ui.Desktop;
import org.zkoss.zk.ui.Session;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.sys.WebAppCtrl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class CkezUploadExtension implements AuExtension {

    private ObjectMapper mapper = new ObjectMapper();

    public CkezUploadExtension() {
    }

    public void init(DHtmlUpdateServlet servlet) throws ServletException {
    }

    public void destroy() {
    }

    public void service(HttpServletRequest request,
                        HttpServletResponse response, String pi) throws ServletException,
            IOException {
        final Session sess = Sessions.getCurrent(false);
        if (sess == null) {
            response.setIntHeader("ZK-Error", HttpServletResponse.SC_GONE);
            return;
        }
        try {
            FileItem item = parseFileItem(request);
            if (item != null) {
                String dtid = request.getParameter("dtid");
                String uuid = request.getParameter("uuid");
                final Desktop desktop = ((WebAppCtrl) sess.getWebApp())
                        .getDesktopCache(sess).getDesktopIfAny(dtid);
                CKeditor editor = (CKeditor) desktop
                        .getComponentByUuidIfAny(uuid);
                String url = editor.write(item.getName(), item.get());
                Map<String, String> result = new HashMap<>();
                result.put("url", url);

                mapper.writeValue(response.getOutputStream(), result);
            }
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            Map<String, String> content = new HashMap<>();
            content.put("message", e.getMessage());
            result.put("error", content);
            mapper.writeValue(response.getOutputStream(), result);
        }
    }

    private FileItem parseFileItem(HttpServletRequest request) throws Exception {
        if (ServletFileUpload.isMultipartContent(request)) {

            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
            servletFileUpload.setHeaderEncoding("UTF-8");
            @SuppressWarnings("unchecked")
            List<FileItem> fileItemsList = servletFileUpload
                    .parseRequest(request);

            for (Iterator<FileItem> it = fileItemsList.iterator(); it.hasNext(); ) {
                FileItem item = it.next();
                if (!item.isFormField()) {
                    return item;
                }
            }
        }
        return null;
    }

}